// Copyright 2009 Google Inc. All Rights Reserved.

/**
 * @fileoverview Logic for the AreYouIn gadget.
 *
 * @author davidbyttow@google.com (David Byttow)
 */

var ANSWER_Yes = 'y';
var ANSWER_No = 'n';
var ANSWER_Maybe = 'm';
var HOST = "http://wave-api.appspot.com/public/gadgets/areyouin";

var DEFAULT_ICONS = {};
DEFAULT_ICONS[ANSWER_Yes] = HOST + '/yes.png';
DEFAULT_ICONS[ANSWER_No] = HOST + '/no.png';
DEFAULT_ICONS[ANSWER_Maybe] = HOST + '/maybe.png';

var DEFAULT_STATUS = {};
DEFAULT_STATUS[ANSWER_Yes] = 'Yes';
DEFAULT_STATUS[ANSWER_No] = 'No';
DEFAULT_STATUS[ANSWER_Maybe] = 'Maybe';

var statusVisible = false;
var participantsReceived = false;
var stateReceived = false;
var canVote = false;

function makeUserKey(id, key) {
  return id + ':' + key;
}

function saveValue(key, value) {
  var state = {};
  state[key] = value;
  wave.getState().submitDelta(state);
}

function onAnswer(answer) {
  if (canVote) {
    var id = wave.getViewer().getId();
    saveValue(makeUserKey(id, 'answer'), answer);
  }
}

function fixUpFields(p, answer) {
  // HACK(davidbyttow): If there is no icon present, use one.
  var icon = p.getThumbnailUrl();
  if (!icon) {
    icon = DEFAULT_ICONS[answer];
  }
  p.icon = icon;

  // HACK(davidbyttow): If the name is actually an id, strip the domain.
  // Currently this happens when the full profile is not yet loaded.
  var name = p.getDisplayName();
  var parts = name.split('@');
  if (parts && parts.length > 1) {
    p.displayName_ = parts[0];
  }
}

function renderPart(templateName, elementName, data) {
  var template = opensocial.template.getTemplate(templateName);
  template.renderInto(document.getElementById(elementName), data);
}

function getStatus(p) {
  return wave.getState().get(makeUserKey(p.getId(), 'status'));
}

function allowStatusChange() {
  statusVisible = true;
  $('#status-link').show();
  $("#status-link").click(function() {
    $(this).hide();
    $('#status-div').show();

    var msg = getStatus(wave.getViewer());
    $('#status-box').val(msg);
    $('#status-box').focus();
    return false;
  });

  $('#status-form').submit(function() {
    $('#status-div').hide();
    $('#status-box').blur();
    $('#status-link').show();
    setStatusMessage($("#status-box").val());
    render();
    return false;
  });
}

function render() {
  var data = {};

  if (!stateReceived || !participantsReceived) {
    return;
  }

  data['stephen.aquila@googlewave.com'] = [];
  data['rockwalrus@googlewave.com'] = [];
  data.total = 0;
  data.responded = false;



  data.canVote = canVote = (wave.getTime() < parseInt(wave.getState().get("deadline", 0)));

  if (canVote) {
    $('#cannotVote').hide();
  } else {
    $('#cannotVote').show();	
  }

  if (wave.getState()) {
    var participants = wave.getParticipants();
    for (var i in participants) {
      var p = participants[i];
      var answer = wave.getState().get(makeUserKey(p.getId(), 'answer'));
      if (!answer) {
        continue;
      }

      if (p == wave.getViewer()) {
        data.responded = true;
        if (!statusVisible) {
          allowStatusChange();
        }
      }

      var msg = getStatus(p);
      if (answer) {
        data[answer].push(p);
        ++data.total;
        fixUpFields(p, answer);
        p.status = msg;
      }
    }
  }

  renderPart('answers-template', 'answer-table', data);
  gadgets.window.adjustHeight();
}

function setStatusMessage(message) {
  var id = wave.getViewer().getId();
  saveValue(makeUserKey(id, 'status'), message);
}

function onStateChanged() {
  stateReceived = true;
  render();
}

function onParticipantChanged() {
  participantsReceived = true;
  render();
}

// TODO(davidbyttow): Remove this hack.
function processTemplate(element, name) {
  var template = os.compileTemplate(element, name);
  os.registerTemplate(template);
  return template;
}

// TODO(davidbyttow): Remove this hack.
function workaroundParsingBugHACK() {
  // Clear the DOM of inline templates..
  for (var i = 0; ; ++i) {
    var div = document.getElementById('_T_template_' + i);
    if (!div) {
      break;
    }
    div.parentNode.removeChild(div);
  }

  // Grab the template nodes.
  var nodes = document.getElementsByTagName("script");
  var templateNodes = [];
  for (var i = 0; i < nodes.length; ++i) {
    var node = nodes[i];
    if (os.Container.isTemplateType_(node.type)) {
      templateNodes.push(node);
    }
  }

  // For this app, we can assume the order of template elements.

  // Register the main template.
  processTemplate(templateNodes[0], 'answers-template');

  // Register the show participant tag.
  var tag = processTemplate(templateNodes[1], 'os:showParticipant');
  var ns = os.getNamespace('os');
  ns['showParticipant'] = os.createTemplateCustomTag(tag);
}

function main() {
  workaroundParsingBugHACK();

  if (wave && wave.isInWaveContainer()) {
    wave.setStateCallback(onStateChanged);
    wave.setParticipantCallback(onParticipantChanged);
  }
  $('#cannotVote').hide();
  $('#status-link').hide();
  $('#status-div').hide();
  $('#status-box').blur();
}

gadgets.util.registerOnLoadHandler(main);

